<template>
  <el-main>
    <!--表单-->
    <el-breadcrumb separator-class="el-icon-arrow-left" style="float:right">
      <el-breadcrumb-item :to="{ path: '/home' }">角色权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>系统管理</el-breadcrumb-item>
    </el-breadcrumb>
    <el-form size="mini" :model="searchForm" label-width="80px">
      <el-row>
        <el-col :span="5">
          <el-form-item label="名称">
            <el-input v-model="queryInfo.name" placeholder="请输入角色名称" @clear="getRoleList" clearable></el-input>
          </el-form-item>
        </el-col>
        <el-button
          class="searchBtn"
          type="primary"
          size="mini"
          icon="el-icon-search"
          @click="getRoleList"
        >查询</el-button>
        <el-button
          class="searchBtn"
          type="primary"
          size="mini"
          icon="el-icon-search"
          @click="showAddDialog"
        >新增</el-button>
      </el-row>
    </el-form>
    <el-table
      size="mini"
      :data="rolelist"
      border
      stripe
      style="width: 100%"
      element-loading-text="Loading..."
      v-loading="listLoading"
      id="selectTable"
    >
      <el-table-column prop="id" label="角色Id"></el-table-column>
      <el-table-column prop="name" label="角色名称"></el-table-column>
      <el-table-column prop="remark" label="备注"></el-table-column>
      <!-- 表格操作栏 -->
      <el-table-column label="操作" align="center" width="250">
        <template slot-scope="scope">
          <el-button @click="showEditDialog(scope.row)" size="mini" type="primary">编辑</el-button>
          <el-button size="mini" @click="assignRole(scope.row)" type="success">分配权限</el-button>
          <el-button size="mini" @click="deleteRole(scope.row)" type="danger">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页区域 -->
    <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="queryInfo.currentPage"
      :page-sizes="[1, 2, 5, 10]"
      :page-size="queryInfo.pageSize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
    ></el-pagination>
    <!--新增角色对话框弹窗-->
    <el-dialog
      :title="dialogTitle"
      :visible.sync="dialogVisible"
      width="25%"
      :close="addDialogClosed"
    >
      <el-form
        :model="addForm"
        :rules="addFormRules"
        ref="addFormRef"
        label-width="70px"
        :inline="false"
      >
        <el-form-item label="角色名称" prop="name">
          <el-input v-model="addForm.name" placeholder="请输入角色名称"></el-input>
        </el-form-item>
        <el-form-item label="角色描述">
          <el-input v-model="addForm.remark" placeholder="请输入角色描述"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addRole">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 修改角色的对话框 -->
    <el-dialog title="修改角色" :visible.sync="editDialogVisible" width="50%" >
      <el-form :model="editForm"  ref="editFormRef" label-width="70px">
        <el-form-item label="角色id">
          <el-input v-model="editForm.id" disabled></el-input>
        </el-form-item>
        <el-form-item label="角色名称" prop="name">
          <el-input v-model="editForm.name" disabled></el-input>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="editForm.remark"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editRoleInfo">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 编辑角色权限对话框 -->
    <el-dialog class="self_dialog" width="25%" :title="dialogTitle" :visible.sync="innerVisible">
      <tree
        :nodes="treeDatas"
        :setting="setting"
        @onCheck="ztreeOnCheck"
        @onCreated="handleCreated"
      />
      <div slot="footer" class="dialog-footer">
        <el-button @click="innerVisible = false">取 消</el-button>
        <el-button type="primary" @click="saveAssign">确 定</el-button>
      </div>
    </el-dialog>
  </el-main>
</template>

<script>
import tree from "vue-giant-tree";
export default {
  components: {
    tree,
  },
  created() {
    if (sessionStorage.getItem("currentPage")) {
      this.queryInfo.currentPage = parseInt(
        sessionStorage.getItem("currentPage")
      );
    }
    if (sessionStorage.getItem("pageSize")) {
      this.queryInfo.pageSize = parseInt(sessionStorage.getItem("pageSize"));
    }
    if (sessionStorage.getItem("name")) {
      const name = sessionStorage.getItem("name");

      this.queryInfo.name = name;
      // alert(this.queryInfo.loginName);
    }

    this.getRoleList();
  },
  data() {
    return {
      checkPermissions:[],
      dialogVisible: false,
      editDialogVisible: false,
      dialogTitle: "",
      pagesize: 2,
      total: 0,
      rolelist: [],
      listLoading: true,
      // 查询到的角色信息对象
      editForm: {
        id: 0,
        remark: "",
        name: "",
      },
      // 获取角色列表的参数对象
      queryInfo: {
        name: "",
        // query: "",
        // 当前的页数
        currentPage: 1,
        // 当前每页显示多少条数据
        pageSize: 2,
      },
      // 添加表单的验证规则对象
      addFormRules: {
        name: [
          { required: true, message: "请输入角色名称", trigger: "blur" },
          {
            min: 3,
            max: 10,
            message: "角色名称的长度在3~10个字符之间",
            trigger: "blur",
          },
        ],
      },
      // 修改表单的验证规则对象
      // editFormRules: {
      //   remark: [
      //     { required: true, message: "请输入用户邮箱", trigger: "blur" },
      //     { validator: checkEmail, trigger: "blur" },
      //   ],
      //   mobile: [
      //     { required: true, message: "请输入用户手机", trigger: "blur" },
      //     { validator: checkMobile, trigger: "blur" },
      //   ],
      // },
      addForm: {
        name: "",
        remark: "",
      },
      searchForm: {
        roleName: "",
      },
      // tableData: [
      //   {
      //     name: "总经理",
      //     remark: "总经理",
      //   },
      //   {
      //     name: "一般管理员",
      //     remark: "一般管理员",
      //   },
      //   {
      //     name: "人事专员",
      //     remark: "人事专员",
      //   },
      // ],
      treeDatas: [],
      saveDatas:[],
      //https://github.com/tower1229/Vue-Giant-Tree
      //https://github.com/tower1229/Vue-Giant-Tree/blob/master/src/App.vue
      innerVisible: false, //控制分配权限弹框显示
      ztreeObj: null, //当前树对象，树创建成功后返回
      setting: {
        check: {
          enable: true, // 树是否显示 复选框或单选按钮
        },
        data: {
          simpleData: {
            enable: true, //是否使用简单数据模式
            //如果设置为 true，必须设置 setting.data.simpleData 内的其他参数: idKey / pIdKey / rootPId，并且让
            //数据满足父子关系。
            idKey: "id",
            pIdKey: "pid",
            rootPId: "0",
          },
        },
        //@onCheck 用于捕获 checkbox / radio 被勾选 或 取消勾选的事件回调函数
        callback: {
          //回调函数
          onCheck: this.ztreeOnCheck, //树选中时回调，用于获取选中的节点数据
        },
      },
    };
  },

  // mounted() {
  //   this.$nextTick(() => {
  //     this.tableHeight = window.innerHeight - 200; //后面的50：根据需求空出的高度，自行调整
  //   });
  // },
  methods: {
    //分页显示列表
    async getRoleList() {
      this.listLoading = true;
      const { data: res } = await this.$http.post(
        "/api/role/getRoleList",
        this.queryInfo
      );
      console.log(res);
      sessionStorage.setItem("currentPage", this.queryInfo.currentPage);
      sessionStorage.setItem("pageSize", this.queryInfo.pageSize);
      sessionStorage.setItem("name", this.queryInfo.name);

      if (res.code !== 200) {
        return this.$message.error(res.msg);
      }
      this.rolelist = res.data;
      console.log(this.rolelist);

      this.total = res.total;
      this.listLoading = false;
    },
    showAddDialog() {
      this.dialogVisible = true;
      this.dialogTitle = "角色新增";
      this.addForm = {
        name: "",
        remark: "",
      };
    },
    async addRole() {
      this.$refs.addFormRef.validate(async (valid) => {
        if (!valid) return;
        // 可以发起添加用户的网络请求
        const { data: res } = await this.$http.post(
          "/api/role/createRole",
          this.addForm
        );

        if (res.code !== 200) {
          this.$message.error(res.msg);
        } else {
          this.$message.success(res.msg);
          // 隐藏添加用户的对话框
          this.dialogVisible = false;
          // 重新获取用户列表数据
          this.getRoleList();
        }
      });
    },
    // 监听添加角色对话框的关闭事件
    addDialogClosed() {
      this.$refs.addFormRef.resetFields();
    },
    //分配权限check选中
    ztreeOnCheck() {
      let checked = this.ztreeObj.getCheckedNodes(true);
      let unchecked=this.ztreeObj.getCheckedNodes(false);
      this.saveDatas=[...checked,...unchecked]

      this.checkPermissions = checked;
      console.log(this.treeDatas);

    },
    //分配权限按钮点击事件
    async assignRole(row) {
      this.roldId = row.id;
      this.dialogTitle = "为【" + row.name + "】分配权限";
      const { data: res } = await this.$http.post(
        "/api/permission/getParentTree?id=" + row.id
        // this.queryInfo
      );
      this.treeDatas = res.data;
      this.saveDatas=res.data;

      this.innerVisible = true;
    },
    async saveAssign() {
      const treeVoList=[]
      // console.log(this.checkPermissions)
      // console.log(this.treeDatas)
      this.saveDatas.map((item,index)=>{
        // console.log(item)
        let data={}
        data['name']=item.name;
        data['id']=item.id;
        data['checked']=item.checked
        data['pid']=item.pid
        data['open']=item.open
        treeVoList[index]=data
      })
      // this.treeDatas.forEach(x=>{
      //   this.checkPermissions.forEach(y=>{
      //     if()
      //   })
      // })
      const { data: res } = await this.$http.post(
        "/api/permission/saveParentTree?id=" + this.roldId,
        {
          treeVoList
        }
        // this.queryInfo
      );
      if(res.code!==200){
         return this.$message.error(res.msg);
      }
      this.innerVisible = false;

      return this.$message.success(res.msg);
       
      //  this.getRoleList();
    },
    //@onCreated 树创建时回调函数
    handleCreated: function (ztreeObj) {
      console.log("加载树完成");
      this.ztreeObj = ztreeObj;
      console.log(this.ztreeObj);
      let firstTree = ztreeObj.getNodes()[0];
      //默认选中第一个
      ztreeObj.selectNode(firstTree);
      //设置节点全部展开
      ztreeObj.expandAll(true);
      //加载完自动点击第一个，加载右边表格
      // this.setting.callback.onClick(null, firstTree.id, firstTree);
    },
    // 监听 pagesize 改变的事件
    handleSizeChange(newSize) {
      // console.log(newSize)
      this.queryInfo.pageSize = newSize;
      this.getRoleList();
    },
    // 监听 页码值 改变的事件
    handleCurrentChange(newPage) {
      console.log(newPage);
      this.queryInfo.currentPage = newPage;
      this.getRoleList();
    },
    async showEditDialog(row) {
      console.log(row);
      this.editForm.name = row.name;
      this.editForm.remark = row.remark;
      this.editForm.id = row.id;
      this.editDialogVisible = true;
    },
    async editRoleInfo() {
      this.$refs.editFormRef.validate(async (valid) => {
        if (!valid) return;
        // 发起修改用户信息的数据请求
        const { data: res } = await this.$http.post(
          "/api/role/updateSaveRole",
          this.editForm
          // {
          //   email: this.editForm.email,
          //   mobile: this.editForm.mobile,
          // }
        );

        if (res.code !== 200) {
          return this.$message.error(res.msg);
        }

        // 关闭对话框
        this.editDialogVisible = false;
        // 刷新数据列表
        this.getRoleList();
        // 提示修改成功
        this.$message.success(res.msg);
      });
    },
  },
};
</script>
<style lang="less" scoped>
.self_dialog {
  display: flex;
  justify-content: center;
  align-items: Center;
  // 第16讲组织管理列表布局
  // 1.1、采用左右侧布局列表
  // 使用组件： 表格组件 分页组件
  overflow: hidden;
}
.self_dialog /deep/ .el-dialog {
  margin: 0 auto !important;
  height: 50%;
  overflow: hidden;
  display: flex;
  flex-direction: column;
  padding-left: 15px;
}
.self_dialog /deep/ .el-dialog .el-dialog__body {
  padding-top: 5px !important;
  overflow: hidden;
  overflow-y: auto;
  margin-bottom: 40px;
}
.self_dialog /deep/ .el-dialog .el-dialog__footer {
  left: 40%;
  bottom: 0;
  position: absolute;
}
/* 全局样式表 */
html,
body,
#app {
  height: 100%;
  margin: 0;
  padding: 0;
  min-width: 1366px;
}

.el-breadcrumb {
  margin-bottom: 15px;
  margin-right: 15px;
  font-size: 15px;
}

.el-card {
  box-shadow: 0 1px 1px rgba(0, 0, 0, 0.15) !important;
}

.el-table {
  margin-top: 15px;
  font-size: 12px;
}

.el-pagination {
  margin-top: 15px;
}

.el-steps {
  margin: 15px 0;
}

.el-step__title {
  font-size: 13px;
}

.ql-editor {
  min-height: 300px;
}
</style>